﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AntiObesity.Base;
using AntiObesity.Base.Managers;

namespace AntiObesity.Services
{
    public partial class UserHome : SecuredPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            UpdateSummary();
            DataBind();
        }

        private void UpdateSummary()
        {
            var bodyHistory = BodyHistoryManager.GetLatestHistory(Session.GetCurrentUser().ID);
            var targetHistory = TargetHistoryManager.GetLatestHistory(Session.GetCurrentUser().ID);
            var bmr = Calculator.BMR(Session.GetCurrentUser(), bodyHistory.Weight, bodyHistory.Height);
            var bmi = Calculator.BMI(bodyHistory.Weight, bodyHistory.Height);
            var consumedCalories = IntakeManager.GetTotalCalories(DateTime.Today, DateTime.Today.Tomorrow(), Session.GetCurrentUser().ID);
            var remainedCalories = 0f;
            var targetBMR = 0f;
            if (targetHistory != null && targetHistory.TargetWeight != 0)
            {
                targetBMR = Calculator.BMR(Session.GetCurrentUser(), targetHistory.TargetWeight, bodyHistory.Height);
                remainedCalories = targetBMR - consumedCalories;
            }
            else
            {
                remainedCalories = bmr - consumedCalories;
            }

            lblCurrentWeight.Text = bodyHistory.Weight.ToString();
            lblCurrentHeight.Text = bodyHistory.Height.ToString();
            lblBMR.Text = bmr.ToString("#.##");
            lblBMI.Text = String.Format("{0:#.##} ({1})", bmi.ToString("#.##"), Calculator.Interpretation(bmi));

            lblRemainedCalories.Text = remainedCalories.ToString("#.##");
            if (targetHistory != null && targetHistory.TargetWeight != 0)
            {
                spnTagetInfo.Visible = true;
                lblTargetWeight.Text = targetHistory.TargetWeight.ToString("#.##");
                lblTargetBMR.Text = targetBMR.ToString("#.##");
            }
        }

        protected void btnRecordIntake_Click(object sender, EventArgs e)
        {
            Response.Redirect("RecordIntake.aspx");
        }

        protected void btnSetTarget_Click(object sender, EventArgs e)
        {
            Response.Redirect("SetTarget.aspx");
        }

        protected void btnLogout_Click(object sender, EventArgs e)
        {
            Session.SetCurrentUser(null);
            Response.Redirect("Login.aspx");
        }
    }
}
